package XPStruct;

import org.msgpack.core.MessagePack;
import org.msgpack.core.MessagePacker;
import java.io.ByteArrayOutputStream;
import java.util.UUID;

//电脑设备(机位) 发送到 傀儡设备(手机端) 的执行命令参数
public class S2CStruct {
    public String      action;

    public String      guid;    //请求(响应) 编号

    public String      kid;	    //设备(进程) 编号

    public long        time;    //发送(响应) 时间

    public byte[]      args;

    //获取 应用的 名称信息
    public static String guid() {
        return UUID.randomUUID().toString();
    }

    public byte[] serialize(){
        try (ByteArrayOutputStream outStream = new ByteArrayOutputStream()) {
            MessagePacker packer = MessagePack.newDefaultPacker(outStream);
            packer.packArrayHeader(5); // 开始一个包含5个元素的数组
            packer.packString(action);
            packer.packString(guid);
            packer.packString(kid);
            packer.packLong(time);
                packer.packBinaryHeader(args.length); // 指定字节数组的长度
                packer.writePayload(args);
            packer.close();
            return outStream.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    //打包参数列表
    public static byte[] MSGPackParams(Object... args){
        try (ByteArrayOutputStream outStream = new ByteArrayOutputStream()) {
            MessagePacker packer = MessagePack.newDefaultPacker(outStream);
            //处理参数长度
            packer.packArrayHeader(args.length);
            // 打包每个参数
            for (Object arg : args) {
                if (arg instanceof String) {
                    packer.packString((String) arg);
                } else if (arg instanceof Integer) {
                    packer.packInt((Integer) arg);
                } else if (arg instanceof Double) {
                    packer.packDouble((Double) arg);
                }else if (arg instanceof Boolean) {
                    packer.packBoolean((Boolean) arg);
                }else if (arg instanceof Long) {
                    packer.packLong((long) arg);
                }else //根据需要添加类型, 未知类型则报错
                    return null;
            }
            packer.close();
            //
            return outStream.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }




}
